<?php

namespace App\SubApps\Account\Middleware;

use App\Providers\RouteServiceProvider;
use App\SubApps\Account\Entities\OauthAppsEntity;
use Closure;
use Hilaoyu\Utils\UtilHttp;
use Hilaoyu\Utils\UtilSupport;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

class OauthAppMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param string|null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if(in_array(Route::currentRouteName(),[
            'web.laravel-extend.services.auth.login',
            'web.laravel-extend.services.auth.register',
            'web.laravel-extend.services.auth.reset-pass',
            'web.laravel-extend.services.auth.logout',
        ])){
            UtilSupport::tryQuiet(function () {
                session()->forget('oauth_data');
            });
        }
        $oauth_data = [];
        $oauth_app_id = $request->input('oauth_app_id', '');
        if ($oauth_app_id) {
            UtilSupport::tryQuiet(function () {
                session()->forget('oauth_data');
            });
            $OauthAppsEntity = new OauthAppsEntity();
            $oauth_app = $OauthAppsEntity->findById($oauth_app_id);
            if (!$oauth_app) {
                return comResponse()->failed('应用不存在')->withErrors('应用不存在', 'oauth_app_id')->back();
            }

            $back_url = $request->input('back_url', '');
            $back_url = urldecode($back_url);
            $return_urls = collect($oauth_app->return_url);


            if (empty($back_url) || !($return_item = collect($oauth_app->return_url)->first(function ($item) use ($back_url) {
                    return $back_url == data_get($item, 'url', '');
                }))) {
                return comResponse()->failed('回调地址错误')->withErrors('回调地址错误', 'back_url')->back();
            }

            $return_url_others = $return_urls->filter(function ($item) use ($back_url) {
                return $back_url != data_get($item, 'url', '');
            })->toArray();

            $state = $request->input('state', '');

            $oauth_app->addHidden('secret');
            $oauth_data = [
                'app' => $oauth_app,
                'back_url' => $back_url,
                'back_name' => data_get($return_item,'name',''),
                'state' => $state,
                'return_url_others' => $return_url_others,
            ];

        }else{
            $oauth_data = UtilSupport::tryQuiet(function () {
                return session('oauth_data');
            });
        }
        $request->offsetSet('oauth', $oauth_data);
        comResponse()->with($oauth_data, 'oauth_data');

        $oauth_apps = collect();
        if(empty($oauth_data)){
            $OauthAppsEntity = new OauthAppsEntity();
            $oauth_apps = $OauthAppsEntity->select(function ($query){
                return $query->where('status','=','1');
            },['updated_at'=>'desc'],5);
        }
        comResponse()->with($oauth_apps,'oauth_apps');

        $response = $next($request);


        UtilSupport::tryQuiet(function () use ($oauth_data) {
            session(['oauth_data' => $oauth_data]);
        });
        return $response;
    }
}
